package random.fox.p2p.api;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by wq on 15/3/19.
 */
class PostImageRequest extends JsonObjectRequest {
    private File imageFile;
    private final long boundary;

    public PostImageRequest(String url, ApiClient.CallBack callback, Map<String, String> params, File imageFile) {
        super(url, callback, params);
        this.imageFile = imageFile;
        boundary = System.currentTimeMillis();
    }

    @Override
    public String getBodyContentType() {
        return "multipart/form-data; boundary="+boundary;
    }

    @Override
    public byte[] getBody() {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        Map<String, String> params = getParams();
        if (params != null) {
            Set<String> keySet = params.keySet();
            Iterator<String> iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = params.get(key);
                builder.addTextBody(key, value, ContentType.create("text/plain", Consts.UTF_8));
            }

            if (imageFile!=null&&imageFile.exists()){
                builder.addPart(imageFile.getName(),new FileBody(imageFile,ContentType.DEFAULT_BINARY,imageFile.getName()));
            }
        }
        HttpEntity entity = builder
                .setBoundary(""+boundary)
                .build();
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            entity.writeTo(bytes);
            return bytes.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.getBody();
    }

}